<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 主体内容 -->
    <div class="mx-auto max-w-8xl px-4 py-6">
      <!-- 标题和操作按钮 -->
      <div class="flex items-center justify-between mb-6">
        <div class="flex space-x-3">
          <el-button type="primary" class="!rounded-button whitespace-nowrap" @click="showAddDialog">
            <el-icon class="mr-1"><Plus /></el-icon>
            新增分类
          </el-button>
        </div>
      </div>

      <!-- 搜索筛选区 -->
      <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <el-input
              v-model="filterForm.name"
              placeholder="搜索分类名称/ID"
              clearable
              class="!rounded-button"
              @input="getPage"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-select
              v-model="filterForm.categoryType"
              placeholder="分类类型"
              clearable
              class="!rounded-button"
              @change="getPage"
          >
            <el-option label="全部" value="" />
            <el-option label="服务" :value="1" />
            <el-option label="商品" :value="2" />
          </el-select>

          <el-select
              v-model="filterForm.status"
              placeholder="状态"
              clearable
              class="!rounded-button"
              @change="getPage"
          >
            <el-option label="推荐" :value="1" />
            <el-option label="不推荐" :value="0" />
          </el-select>

          <el-select
              v-model="filterForm.parentId"
              placeholder="请选择父分类"
              clearable
              class="!rounded-button"
              @change="getPage"
          >
            <el-option
                v-for="item in categories"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </div>
      </div>
      <!-- 表格区域 -->
      <div class="bg-white rounded-lg shadow-sm overflow-hidden">
        <el-table
            :data="filteredProducts"
            style="width: 100%"
            border
            stripe
            v-loading="loading"
            @sort-change="handleSortChange"
        >
          <el-table-column prop="id" label="分类ID" width="100" sortable="custom" />

          <el-table-column prop="name" label="分类名称" width="180" />

          <el-table-column label="分类类型" width="120">
            <template #default="{row}">
              <el-tag :type="row.categoryType === 1 ? 'primary' : 'success'">
                {{ row.categoryType === 1 ? '服务' : '商品' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="父分类" width="150">
            <template #default="{row}">
              <el-tag v-if="row.parentId" type="primary">
                {{ row.parentId }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="描述" width="600">
            <template #default="{row}">
              <span v-if="row.description" type="primary">
                {{ row.description }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="90">
            <template #default="{row}">
              <el-tag :type="row.status ? 'success' : 'danger'">
                {{ row.status == 1 ? '推荐' : '不推荐' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="175" fixed="right">
            <template #default="{row}">
              <div class="flex space-x-2">
                <el-button size="small" type="primary" @click="editProduct(row.id)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button size="small" type="danger" @click="confirmDelete(row)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="p-4 flex justify-end">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑餐品' : '新增餐品'"
        width="50%"
    >
      <el-form :model="form" label-width="100px" ref="formRef">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>

        <el-form-item label="分类类型" prop="type">
          <el-radio-group v-model="form.categoryType">
            <el-radio :value="1">服务</el-radio>
            <el-radio :value="2">商品</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="父分类" prop="category_id">
          <el-select
              v-model="form.parentId"
              placeholder="请选择父分类"
              clearable
              class="!rounded-button"
              @change="getPage"
          >
            <el-option
                v-for="item in categories"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="是否推荐" prop="status">
          <el-switch v-model="form.status"
                     active-value=1
                     inactive-value=0
                     active-text="推荐"
                     inactive-text="不推荐" />
        </el-form-item>

        <el-form-item label="分类描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script lang="js" setup>
import { ref, computed, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Plus,
  Upload,
  Star,
  Search,
  View,
  Edit,
  Delete, UploadFilled
} from '@element-plus/icons-vue';
import categoryApi from "@/api/admin/categoryApi.js";
import {useTokenStore} from "@/stores/token.js";

const tokenStore = useTokenStore();
//上传图片
const headers = computed(() => {
  let token = tokenStore.tokenStr;
  return {
    token
  }
})

const categories = ref();

// 表格相关状态
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref('');
const sortProp = ref('');
const sortOrder = ref('');

// 筛选条件
const filterForm = ref({
  name: '',
  categoryType: '',
  status: '',
  parentId: '',
});

// 对话框状态
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref();

// 表单数据
const form = ref({
  id: 0,
  name: '',
  parentId: 1,
  description: '',
  categoryType: 1,
  status: 1,
});
// 分页数据
const pageData = ref();

// 获取所有父分类数据
const getCategory = ()=>{
  let category = {
    parentId: 0,
    categoryType: 2,
  };
  categoryApi.selectByPage(null, null, category)
      .then(resp => {
        categories.value = resp.data;
        let category = {
          id: 0,
          name: '无',
        };
        categories.value.unshift(category);
      })
};
// 获取分页数据
const getPage = ()=>{
  categoryApi.selectByPage(currentPage.value, pageSize.value, filterForm.value)
      .then(resp => {
        pageData.value = resp.data;
        total.value = pageData.value.total;
      })
};
// 计算分类列表
const filteredProducts = computed(() => {
  // 保证pageData.value存在
  if (!pageData.value) {
    return [];
  }
  let result = pageData.value.list;
  if (!categories.value) {
    return [];
  }
  let categoryList = categories.value;
  // 获取分类数据
  result.forEach(item => {
    for (let i = 0; i < categoryList.length; i++) {
      let  category = categoryList[i];
      // 判断是否为父分类
      if (item.parentId === 0) {
        item.parentId = '父分类';
      }else {
        if (category.id === item.parentId){
          item.parentId = category.name;
        }
      }
    }
  })

  // 排序
  if (sortProp.value && sortOrder.value) {
    result.sort((a, b) => {
      const valA = a[sortProp.value];
      const valB = b[sortProp.value];
      if (sortOrder.value === 'ascending') {
        return compareValues(valA,valB)
      } else {
        return compareValues(valB,valA)
      }
    });
  }
  return result;
});
// 通用排序规则
const compareValues = (a, b)=>{
  // 数字类型比较
  if (typeof a === 'number' && typeof b === 'number') {
    return a - b;
  }

  // 日期类型比较
  if (a instanceof Date && b instanceof Date) {
    return a.getTime() - b.getTime();
  }

  // 字符串类型（支持中文）
  return String(a).localeCompare(String(b), 'zh');
}
// 分页数据
const pagedProducts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  console.log(start)
  console.log(end)
  return filteredProducts.value.slice(start, end);
});
// 显示新增对话框
const showAddDialog = () => {
  isEdit.value = false;
  form.value = {
    id: 0,
    name: '',
    parentId: '',
    description: '',
    categoryType: 1,
    status: 1,
  };
  dialogVisible.value = true;
  nextTick(() => {
    formRef.value?.clearValidate();
  });
};

// 编辑分类
const editProduct = (id) => {
  categoryApi.selectByID(id)
      .then(resp => {
        let category = resp.data;
        if (category != null) {
          form.value = category;
          form.value.status = String(category.status);
          isEdit.value = true;
          dialogVisible.value = true;
          nextTick(() => {
            formRef.value?.clearValidate();
          });
        } else {
          ElMessage.error('分类不存在');
        }
      })
      .catch(error => {
        ElMessage.error('分类不存在');
      });

};

// 提交表单
const submitForm = () => {
  // 判断是否是新增还是编辑
  if (isEdit.value) {
      categoryApi.update(form.value)
          .then(resp => {
            if (resp.code === 10000){
              dialogVisible.value = false;
              getPage();
              // 重置form里面的数据
              form.value = {
                id: 0,
                name: '',
                parentId: '',
                description: '',
                categoryType: 1,
                status: 1,
              }
              ElMessage.success(resp.msg)
            }else {
              ElMessage.error(resp.msg)
            }
          })
  }else {
    categoryApi.insert(form.value)
        .then(resp => {
          if (resp.code === 10000){
            dialogVisible.value = false;
            getPage();
            // 重置form里面的数据
            form.value = {
              id: 0,
              name: '',
              parentId: '',
              description: '',
              categoryType: 1,
              status: 1,
            }
            ElMessage.success(resp.msg)
          }else {
            ElMessage.error(resp.msg)
          }
        })
  }
};

// 删除分类
const confirmDelete = (category) => {
  ElMessageBox.confirm(
      `确定要删除分类 "${category.name}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    categoryApi.delete(category.id)
        .then(resp => {
          if (resp.code === 10000){
            ElMessage.success('删除成功');
            getPage();
          }else {
            ElMessage.error(resp.msg)
          }
        })
    ElMessage.success('删除成功');
  }).catch(() => {
    // 取消删除
  });
};


// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  getPage();
};

// 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getPage();
};

// 排序变化
const handleSortChange = ( {prop, order} ) => {
  sortProp.value = prop;
  sortOrder.value = order;
};


getPage();
getCategory();
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

:deep(.el-table .cell) {
  padding-left: 8px;
  padding-right: 8px;
}

:deep(.el-table th.el-table__cell) {
  background-color: #f5f5f5;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell) {
  background-color: #fafafa;
}

:deep(.el-table .el-table__body tr:hover > td.el-table__cell) {
  background-color: #f0f7ff;
}
</style>
